<?php

namespace app\api\model;


class Product extends Base
{
    protected $hidden = [
        'delete_time', 'update_time', 'create_time', 'from', 'category_id',
        'pivot', 'img_id'
    ];

    /**
     * 获取商品详情图片，一对多
     * @return \think\model\relation\BelongsToMany
     */
    public function productImages()
    {
        return $this->hasMany('productImage', 'product_id', 'id')->order('order', 'asc');
    }

    /**
     * 获取商品描述信息
     * @return \think\model\relation\BelongsTo
     */
    public function productProperty()
    {
        // 一对多的关系
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    /**
     * 获取商品详情
     * @param $productId
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDetail($productId)
    {
        return self::with(['productImages.imgUrl','productProperty'])->find($productId);
    }

    /**
     * 获取最近新品
     * @param $count
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getProductNewList($count)
    {
        return self::limit(0, $count)
            ->where('delete_time', null)
            ->order('create_time', 'desc')
            ->select();
    }

    /**
     * 根据分类ID获取商品列表
     * @param $category_id
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getByCategory($category_id)
    {
        return self::where('category_id', '=', $category_id)
            ->where('delete_time', null)
            ->order('create_time', 'desc')
            ->select();
    }

    /**
     * 格式化Url地址
     * @param $value
     * @param $data
     * @return string
     */
    public function getMainImgUrlAttr($value, $data)
    {
        return $this->prefixImgUrl($value, $data);
    }

    /**
     * 根据下单的商品ID获取商品信息
     * @param $ids
     * @return bool
     */
    public static function getProductsByOrderProducts($ids)
    {
        if (empty($ids))
        {
            return false;
        }
        return self::select($ids)
            ->toArray();
    }
}
